<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="店铺名称" prop="shopName">
        <el-input
            v-model="queryParams.shopName"
            placeholder="请输入店铺名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提交时间" prop="submitTime">
        <el-date-picker clearable
          v-model="queryParams.submitTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择提交时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审核时间" prop="reviewTime">
        <el-date-picker clearable
          v-model="queryParams.reviewTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择审核时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['order:shopInfoChange:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['order:shopInfoChange:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['order:shopInfoChange:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['order:shopInfoChange:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shopInfoChangeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="变更记录ID" align="center" prop="shopChangeId" />-->
      <el-table-column label="店铺名称" align="center" prop="shopName" />
      <el-table-column label="变更内容" align="center" prop="changeContent" />
      <el-table-column label="审核状态" align="center">
        <template #default="scope">
          <!-- 动态绑定样式类 -->
          <span :class="getStatusCode(scope.row.changeStatus)">
        {{ scope.row.changeStatus }}
      </span>
        </template>
      </el-table-column>
      <el-table-column label="提交时间" align="center" prop="submitTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.submitTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="center" prop="reviewTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reviewTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="失败原因" align="center" prop="failReason" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="CircleCheck"
              @click="openAudit(scope.row)"
              v-hasPermi="['order:shopInfoChange:edit']"
          >审核</el-button>
          <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['order:shopInfoChange:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="变更审核" v-model="auditOpen" width="480px" append-to-body>
      <el-form ref="auditRef" :model="auditForm" :rules="auditRules" label-width="90px">
        <el-form-item label="审核结果" prop="decision">
          <el-radio-group v-model="auditForm.decision">
            <el-radio label="PASS">通过</el-radio>
            <el-radio label="REJECT">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="auditForm.decision === 'REJECT'" label="拒绝原因" prop="failReason">
          <el-input v-model="auditForm.failReason" type="textarea" :rows="3" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditOpen=false">取 消</el-button>
          <el-button type="primary" @click="submitAudit">提 交</el-button>
        </div>
      </template>
    </el-dialog>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改店铺信息变更记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="shopInfoChangeRef" :model="form" :rules="rules" >
        <el-form-item label="店铺ID" prop="shopId">
          <el-input v-model="form.shopId" placeholder="请输入店铺ID" />
        </el-form-item>
        <el-form-item label="变更内容">
          <editor v-model="form.changeContent" :min-height="192"/>
        </el-form-item>
        <el-form-item label="提交时间" prop="submitTime">
          <el-date-picker clearable
            v-model="form.submitTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择提交时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核时间" prop="reviewTime">
          <el-date-picker clearable
            v-model="form.reviewTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择审核时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="失败原因" prop="failReason">
          <el-input v-model="form.failReason" placeholder="请输入失败原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ShopInfoChange">
import { listShopInfoChange, getShopInfoChange, delShopInfoChange, addShopInfoChange, updateShopInfoChange } from "@/api/order/shopInfoChange"
import {getShop, listShop} from "@/api/order/shop.js";

const { proxy } = getCurrentInstance()

const shopInfoChangeList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shopName: null,
    changeContent: null,
    changeStatus: null,
    submitTime: null,
    reviewTime: null,
  },
  rules: {
    shopId: [
      { required: true, message: "店铺ID不能为空", trigger: "blur" }
    ],
    changeContent: [
      { required: true, message: "变更内容不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询店铺信息变更记录列表 */
function getList() {
  loading.value = true
  listShopInfoChange(queryParams.value).then(async response => {
    // 1. 获取原始信息变更列表
    const initialInfoChangeList = response.rows
    // console.log(response.rows)
    total.value = response.total
    // 2. 为每条数据添加店铺名称
    const infoChangeList = await Promise.all(
        initialInfoChangeList.map(async (shopInfoChange) => {
          // console.log(shop)
          try {
            // 调用接口获取商家信息（包含联系人姓名）
            const shopInfo = await getShop(shopInfoChange.shopId)
            //console.log(businessInfo.data.businessName)
            // 返回合并后的数据（原信息变更信息 + 店铺名称）
            return {
              ...shopInfoChange,
              shopName: shopInfo.data.shopName || '未知店名'
            }
          } catch (error) {
            console.error(`获取商家${shopInfoChange.shopId}信息失败:`, error)
            // 即使获取失败也保留原始店铺信息，避免整条数据丢失
            return {
              ...shopInfoChange,
              shopName: '获取失败'
            }
          }
        })
    )
    // 3. 更新店铺列表
    shopInfoChangeList.value = infoChangeList
    loading.value = false
     console.log(shopInfoChangeList.value)
  }).catch(error => {
    console.error('查询店铺变更信息列表失败:', error)
    loading.value = false
  })
}

const getStatusCode = (status) => {
  const statusMap = {
    // 字符串状态示例
    '待审核': 'status-pending',
    '通过': 'status-approved',
    '拒绝': 'status-rejected',
  };
  return `status-tag ${statusMap[status] || 'status-unknown'}`;
};

// 审核弹窗状态
const auditOpen = ref(false)
const auditForm = reactive({
  shopChangeId: null,
  decision: 'PASS',   // PASS | REJECT
  failReason: ''      // 拒绝时必填
})
const auditRules = {
  decision: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  failReason: [{
    validator: (rule, value, cb) => {
      if (auditForm.decision === 'REJECT' && (!value || !String(value).trim())) {
        return cb(new Error('请输入拒绝原因'))
      }
      cb()
    }, trigger: 'blur'
  }]
}

// 打开审核弹窗，回显数据
function openAudit(row) {
  auditForm.shopChangeId = row.shopChangeId
  auditForm.decision = row.changeStatus === '拒绝' ? 'REJECT' : 'PASS'
  auditForm.failReason = row.failReason || ''
  auditOpen.value = true
}

// 提交审核
function submitAudit() {
  proxy.$refs.auditRef.validate(valid => {
    if (!valid) return
    const d = new Date()
    const today = `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`

    const payload = {
      shopChangeId: auditForm.shopChangeId,
      changeStatus: auditForm.decision === 'PASS' ? '通过' : '拒绝',
      reviewTime: today,
      failReason: auditForm.decision === 'REJECT' ? auditForm.failReason : null
    }

    updateShopInfoChange(payload).then(() => {
      proxy.$modal.msgSuccess('审核提交成功')
      auditOpen.value = false
      getList()
    })
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    shopChangeId: null,
    shopId: null,
    changeContent: null,
    changeStatus: null,
    submitTime: null,
    reviewTime: null,
    failReason: null
  }
  proxy.resetForm("shopInfoChangeRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.shopChangeId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加店铺信息变更记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _shopChangeId = row.shopChangeId || ids.value
  getShopInfoChange(_shopChangeId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改店铺信息变更记录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["shopInfoChangeRef"].validate(valid => {
    if (valid) {
      if (form.value.shopChangeId != null) {
        updateShopInfoChange(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addShopInfoChange(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _shopChangeIds = row.shopChangeId || ids.value
  proxy.$modal.confirm('是否确认删除店铺信息变更记录编号为"' + _shopChangeIds + '"的数据项？').then(function() {
    return delShopInfoChange(_shopChangeIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('order/shopInfoChange/export', {
    ...queryParams.value
  }, `shopInfoChange_${new Date().getTime()}.xlsx`)
}

getList()
</script>
<style scoped>
/* 基础标签样式 */
.status-tag {
  display: inline-block;
  padding: 3px 10px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
}

/* 待审核状态 - 灰色 */
.status-pending {
  color: #6b7280;
  background-color: #f3f4f6;
}

/* 审核通过状态 - 绿色 */
.status-approved {
  color: #10b981;
  background-color: #dcfce7;
}

/* 审核拒绝状态 - 红色 */
.status-rejected {
  color: #ef4444;
  background-color: #fee2e2;
}

/* 未知状态 - 浅灰色 */
.status-unknown {
  color: #9ca3af;
  background-color: #f9fafb;
}
</style>
